package com.hujiang.basic.search.handler.impl.model;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import java.util.Date;

@Data
public class FullIndexTask {

    private int taskId;
    private String alias;
    private String index;
    private String newIndex;
    private TaskState state;
    private String message;
    private String url;
    private String runningNode;
    private String owner;
    private long from;
    private int size;
    private int retryCount;
    private String customData;
    private Date updateAt;
    private Date createAt;

    public static FullIndexTask buildDefault(FullIndexRquest req, String index, int size, String name) {
        Date now = new Date();
        FullIndexTask task = new FullIndexTask();
        task.setAlias(req.getIndexName());
        task.setIndex(index);
        task.setNewIndex(buildNewIndexName(index));
        task.setUrl(req.getUrl());
        task.setRetryCount(0);
        task.setState(TaskState.Ready);
        task.setFrom(0);
        task.setCreateAt(now);
        task.setUpdateAt(now);
        task.setMessage("");
        task.setSize(size);
        task.setOwner(req.getOwner());
        return task;
    }

    private static String buildNewIndexName(String indexName) {
        String[] parts = indexName.split("_");
        if (0 == parts.length) {
            return DateTime.now().toString("yyyyMMddHHmmss");
        } else if (1 == parts.length) {
            return parts[0] + "_" + DateTime.now().toString("yyyyMMddHHmmss");
        } else {
            parts[parts.length - 1] = DateTime.now().toString("yyyyMMddHHmmss");
            return StringUtils.join(parts, '_');
        }
    }

    public String errorClues() {
        return url + ", " + message;
    }
}
